package com.sxz.sbs.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * * <pre>
 *     author : tian
 *     e-mail : 644183234@qq.com
 *     time   : 2018/01/30
 *     desc   :
 *     version: 1.0
 * </pre>
 */

public class TimeUtils {
    public static String timeGap(String starTime) {
        long formattingtime = 0;
        long TimeCha ;
        String  returnString = "";
        Calendar calendar=Calendar.getInstance();
        String currentYear = String.valueOf(calendar.get(Calendar.YEAR));
        SimpleDateFormat dataformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long currenttime = calendar.getTimeInMillis();
        try {//如果你的初始时间是格式化过的,则需要先转化成毫秒值
            formattingtime = dataformat.parse(starTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
//这里需要注意,因为获取的时间因为时差的缘故已经自动加上了8小时的时间,所以这里需要减去.如果不减去,就算是你刚刚发布的动态也会显示是8小时之前
        TimeCha =((currenttime-formattingtime)/1000);//将毫秒值转化成分钟数
        StringBuffer str=new StringBuffer();
        if (TimeCha> 0&TimeCha<60){
            returnString = str.append("刚刚").toString();
        }else if (TimeCha>=60&&TimeCha<3600){
            returnString = str.append(TimeCha / 60 + "分钟前").toString();
        }else if (TimeCha>=3600&&TimeCha<3600*24){
            returnString = str.append(TimeCha / 3600 + "小时前").toString();

        }else if (TimeCha>=3600*1*24&&TimeCha<3600*2*24){
            returnString = str.append("1天前").toString();
        }else if (TimeCha>=3600*2*24&&TimeCha<3600*3*24){
            returnString = str.append("2天前").toString();
        }else if (TimeCha>=3600*3*24&&TimeCha<3600*4*24){
            returnString = str.append("3天前").toString();
        }else if (TimeCha>=3600*4*24){
            try {
                returnString = str.append(starTime.split(" ")[0]).toString();
                String[] arr = returnString.split("-");
                if (currentYear.equals(arr[0])) {
                    returnString = arr[1]+"月" + arr[2] + "日";
                } else {
                    returnString = arr[0]+"年" +arr[1]+"月" + arr[2] + "日";
                }
            }catch (Exception e) {
                return returnString;
            }
        }
        return returnString;
    }
}
